package com.example.videoconverter;

import ws.schild.jave.*;
import ws.schild.jave.info.*;
import ws.schild.jave.encode.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 视频转换器类，提供AVI转MP4功能
 * 使用JAVE库进行视频格式转换
 */
public class VideoConverter {
    private static final Logger logger = LoggerFactory.getLogger(VideoConverter.class);
    
    // 默认视频参数
    private static final int DEFAULT_VIDEO_BITRATE = 2000000; // 2Mbps
    private static final int DEFAULT_AUDIO_BITRATE = 128000;  // 128kbps
    private static final double DEFAULT_FRAME_RATE = 30.0;
    
    /**
     * 将AVI文件转换为MP4格式
     * 
     * @param inputPath 输入AVI文件路径
     * @param outputPath 输出MP4文件路径
     * @throws RuntimeException 当转换失败时抛出
     */
    public void convertAviToMp4(String inputPath, String outputPath) throws RuntimeException {
        convertAviToMp4(inputPath, outputPath, DEFAULT_FRAME_RATE);
    }
    
    /**
     * 将AVI文件转换为MP4格式，指定帧率
     * 
     * @param inputPath 输入AVI文件路径
     * @param outputPath 输出MP4文件路径
     * @param frameRate 目标帧率
     * @throws RuntimeException 当转换失败时抛出
     */
    public void convertAviToMp4(String inputPath, String outputPath, double frameRate) throws RuntimeException {
        File inputFile = new File(inputPath);
        File outputFile = new File(outputPath);
        
        // 验证输入文件
        if (!inputFile.exists()) {
            throw new RuntimeException("输入文件不存在: " + inputPath);
        }
        
        if (!inputFile.canRead()) {
            throw new RuntimeException("无法读取输入文件: " + inputPath);
        }
        
        // 创建输出目录
        File outputDir = outputFile.getParentFile();
        if (outputDir != null && !outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                throw new RuntimeException("无法创建输出目录: " + outputDir.getAbsolutePath());
            }
        }
        
        logger.info("开始转换: {} -> {}", inputPath, outputPath);
        
        try {
            // 创建编码器
            Encoder encoder = new Encoder();
            
            // 设置音频属性
            AudioAttributes audioAttributes = new AudioAttributes();
            audioAttributes.setCodec("aac");
            audioAttributes.setBitRate(DEFAULT_AUDIO_BITRATE);
            
            // 设置视频属性
            VideoAttributes videoAttributes = new VideoAttributes();
            videoAttributes.setCodec("libx264");
            videoAttributes.setBitRate(DEFAULT_VIDEO_BITRATE);
            videoAttributes.setFrameRate((int) frameRate);
            
            // 设置编码属性
            EncodingAttributes encodingAttributes = new EncodingAttributes();
            encodingAttributes.setInputFormat("avi");
            encodingAttributes.setOutputFormat("mp4");
            encodingAttributes.setAudioAttributes(audioAttributes);
            encodingAttributes.setVideoAttributes(videoAttributes);
            
            // 执行转换
            encoder.encode(new MultimediaObject(inputFile), outputFile, encodingAttributes);
            
            logger.info("转换完成: {}", outputPath);
            
        } catch (Exception e) {
            logger.error("转换过程中发生错误", e);
            throw new RuntimeException("视频转换失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取视频文件信息
     * 
     * @param videoPath 视频文件路径
     * @return 包含视频信息的Map
     * @throws RuntimeException 当文件读取失败时抛出
     */
    public Map<String, Object> getVideoInfo(String videoPath) throws RuntimeException {
        File videoFile = new File(videoPath);
        if (!videoFile.exists()) {
            throw new RuntimeException("视频文件不存在: " + videoPath);
        }
        
        Map<String, Object> info = new HashMap<>();
        
        try {
            MultimediaObject multimediaObject = new MultimediaObject(videoFile);
            MultimediaInfo multimediaInfo = multimediaObject.getInfo();
            
            if (multimediaInfo.getVideo() != null) {
                ws.schild.jave.info.VideoInfo videoInfo = multimediaInfo.getVideo();
                info.put("width", videoInfo.getSize() != null ? videoInfo.getSize().getWidth() : 0);
                info.put("height", videoInfo.getSize() != null ? videoInfo.getSize().getHeight() : 0);
                info.put("frameRate", videoInfo.getFrameRate());
                info.put("videoCodec", videoInfo.getDecoder());
                info.put("videoBitRate", videoInfo.getBitRate());
            }
            
            if (multimediaInfo.getAudio() != null) {
                ws.schild.jave.info.AudioInfo audioInfo = multimediaInfo.getAudio();
                info.put("audioChannels", audioInfo.getChannels());
                info.put("sampleRate", audioInfo.getSamplingRate());
                info.put("audioCodec", audioInfo.getDecoder());
                info.put("audioBitRate", audioInfo.getBitRate());
            }
            
            info.put("duration", multimediaInfo.getDuration() / 1000.0); // 转换为秒
            info.put("format", multimediaInfo.getFormat());
            
            logger.info("视频信息获取成功: {}", videoPath);
            
        } catch (Exception e) {
            logger.error("获取视频信息失败", e);
            throw new RuntimeException("无法获取视频信息: " + e.getMessage(), e);
        }
        
        return info;
    }
    
    /**
     * 简化的AVI转MP4转换方法（不依赖JavaCV）
     * 使用默认参数进行快速转换，适用于大多数场景
     * 
     * @param inputPath 输入AVI文件路径
     * @param outputPath 输出MP4文件路径
     * @throws RuntimeException 当转换失败时抛出
     */
    public void simpleConvertAviToMp4(String inputPath, String outputPath) throws RuntimeException {
        File inputFile = new File(inputPath);
        File outputFile = new File(outputPath);
        
        // 基本文件验证
        if (!inputFile.exists()) {
            throw new RuntimeException("输入文件不存在: " + inputPath);
        }
        
        // 创建输出目录
        File outputDir = outputFile.getParentFile();
        if (outputDir != null && !outputDir.exists()) {
            outputDir.mkdirs();
        }
        
        logger.info("开始简化转换: {} -> {}", inputPath, outputPath);
        
        try {
            // 使用JAVE库进行简单转换
            Encoder encoder = new Encoder();
            
            // 设置基本编码属性
            EncodingAttributes encodingAttributes = new EncodingAttributes();
            encodingAttributes.setOutputFormat("mp4");
            
            // 设置视频属性（使用较为通用的设置）
            VideoAttributes videoAttributes = new VideoAttributes();
            videoAttributes.setCodec("libx264");
            videoAttributes.setBitRate(1500000); // 1.5Mbps，适中的码率
            
            // 设置音频属性
            AudioAttributes audioAttributes = new AudioAttributes();
            audioAttributes.setCodec("aac");
            audioAttributes.setBitRate(128000); // 128kbps
            
            encodingAttributes.setVideoAttributes(videoAttributes);
            encodingAttributes.setAudioAttributes(audioAttributes);
            
            // 执行转换
            encoder.encode(new MultimediaObject(inputFile), outputFile, encodingAttributes);
            
            logger.info("简化转换完成: {}", outputPath);
            
        } catch (Exception e) {
            logger.error("简化转换过程中发生错误", e);
            throw new RuntimeException("视频转换失败: " + e.getMessage(), e);
        }
    }

}